package com.Mybatis3源码深度解析.c2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Savepoint;
import java.sql.Statement;
import java.util.Properties;

import org.apache.ibatis.io.Resources;
import org.junit.Test;

/**
 * 获取数据库基本信息
 */
public class SavePointDemo {

    @Test
    public void testSavePoint() {
        try {
        	Class.forName("com.mysql.jdbc.Driver");
            Properties prop = Resources.getResourceAsProperties("hikariPool.properties");
            // 获取Connection对象
            Connection conn = DriverManager.getConnection(prop.getProperty("jdbcUrl"), prop.getProperty("dataSource.user"), prop.getProperty("dataSource.password"));
            String sql1 = "insert into user(create_time, name, password, phone, nick_name) values('2010-10-24 10:20:30','User1','test','18700001111','User1')";
            String sql2 = "insert into user(create_time, name, password, phone, nick_name) values('2010-10-24 10:20:30','User2','test','18700001111','User2')";
            conn.setAutoCommit(false);
            Statement stmt = conn.createStatement();
            stmt.executeUpdate(sql1);
            // 在第一条数据插入后创建保存点
            Savepoint savepoint = conn.setSavepoint("SP1");
            stmt.executeUpdate(sql2);
            // 在第二条数据插入后回滚到保存点
            conn.rollback(savepoint);
            // 最后提交事务。最终事务回滚到保存点位置，所以数据库中只存在一条记录
            conn.commit();
            ResultSet rs  = conn.createStatement().executeQuery("select * from user ");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
